<template>
  <el-card class="mr-20" shadow="never">

    <div class="form-label">
      <span class="content-title">{{ $t('menuStr.protocolProjectListStr') }}</span>
      <span> ( {{ $t('pageStr.protocolProjectDesStr') }} )</span>
    </div>
    <el-table :data="form.projectList" class="mt-20" :header-cell-style="tableHeadStyle">
      <el-table-column :label="$t('pageStr.enableStr')" align="center">
        <template #default="{row}">
          <el-switch :disabled="permissionDisabled()" v-model="row._active" @change="handleStart(row._active,row._load)" active-value="1"
                     inactive-value="0"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('pageStr.projectStr')" align="center" prop="_load"/>
      <el-table-column :label="$t('pageStr.actionStr')" align="center">
        <template #default="{row}">
          <div v-permissionShow class="flex flex-center">
            <span>下载</span>
            <img src="@/assets/icon/download.png" @click="handleDonwload(row)" class="action-img pointer"/>
            <span class="ml-20">删除</span>
            <img src="@/assets/icon/delete.png" @click="handleDelete(row)" class="action-img pointer">
          </div>
        </template>
      </el-table-column>
    </el-table>

  </el-card>
  <el-card class="mt-20 mr-20" shadow="never">
    <el-form :disabled="permissionDisabled()" :model="form" :rules="rules" ref="FormRef" label-position="top" class="goodForm">
      <div class="content-title">{{ $t('menuStr.protocolProjectImportStr') }}</div>
      <el-form-item>
        <template #label>
          <div class="form-label">
            <span>{{ $t('pageStr.projectFileStr') }}</span>
            <span>({{ $t('pageStr.protocolProjectImportDesStr') }})</span>
          </div>
        </template>
        <file-upload url="/protocol/get_upload_project_struct" accept=".tgz" :btn-label="$t('tabsStr.importStr')"
                     @uploadSuccess="onUploaded"/>
      </el-form-item>
    </el-form>
  </el-card>
  <div></div>

</template>

<script setup>
import {inject, reactive, ref, onBeforeMount} from 'vue'
import FileUpload from '@/components/Upload/index.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {
  reqCheckProjectList,
  reqGetProjectList,
  reqImportProject,
  reqSetProjectList
} from '@/api/data-collect/protocol-config'
import {useI18n} from 'vue-i18n'
import {downloadFile,permissionDisabled} from "@/utils";

const {t} = useI18n()

const defaultProjectList = {"workspace": {}};
/**
 * 注入依赖，xml解析对象
 * @type {unknown}
 */
const $x2js = inject('x2js')
/**
 * dom元素挂载前生命周期
 */
onBeforeMount(getData)

/**
 * 获取项目列表并回显
 */
function getData() {
  reqGetProjectList().then((data) => {
    updateProjectList(data)
  })
}

/**
 * 更新项目列表
 * @param data xml格式
 */
function updateProjectList(data) {
  const jsonData = $x2js.xml2js(data) || defaultProjectList;
  const projectArr = []
  if (jsonData.workspace && jsonData.workspace && jsonData.workspace.project) {
    if (!jsonData.workspace.project.length) {
      jsonData.workspace.project = [jsonData.workspace.project]
    }
    jsonData.workspace.project.forEach((item) => {
      projectArr.push({_active: item._active, _load: item._load})
    })
  }
  form.value.projectList = projectArr
  console.log('工程列表', jsonData, form.value)
}


const form = ref({
  projectList: []
})
const tableHeadStyle = {
  'text-align': 'center',
  'background-color': '#F5EFE9',
  'max-width': '1000px'
}
const FormRef = ref(null)
const rules = reactive({})

/**
 * 上传成功后的事件回调
 */
function onUploaded(data) {
  const projectName = checkProjectStruct(data);
  const hasProjectName = form.value.projectList.some((item) => {
    return item._load == projectName
  })
  console.log('上传完成的回调\n', data, '\nprojectName\n', projectName, hasProjectName)
  if (projectName) {
    if (hasProjectName) {
      ElMessageBox.confirm('是否覆盖同名的工程', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        importProjectConfirm(projectName)
      }).catch(() => {
        ElMessage.info(t('alertStr.errorUploadStr'))
      })
    } else {
      if (form.value.projectList.length >= 10) {
        ElMessage.error(t('alertStr.errReachMaxProjectCount'))
      } else {
        importProjectConfirm(projectName);
      }
    }
  } else {
    ElMessage.error(t('alertStr.errFileFormat'))
  }
}

/**
 * 导入项目确认
 * @param projectName 项目名
 */
function importProjectConfirm(projectName) {
  reqImportProject().then((res) => {
    if (res.importInfo == 0) {
      handleStart('1', projectName)
    }
  })
}

/**
 * 检查项目列表结构
 * @param projectStruct
 * @returns {null}
 */
function checkProjectStruct(projectStruct) {
  projectStruct = projectStruct.split("\n");
  let projectName = null;
  if (projectStruct.length && projectStruct.length > 2) {
    const folder = projectStruct[0];
    const projectNameTmp = folder.replace("/", "");
    for (let index = 1; index < projectStruct.length - 1; index++) {
      const path = projectStruct[index];
      const regEpj = new RegExp('^' + projectNameTmp + '\/[^.\/]+\.epj$');
      if (regEpj.test(path)) {
        projectName = projectNameTmp;
      }
      const regPath = new RegExp('^' + projectNameTmp + '\/');
      if (!regPath.test(path)) {
        projectName = null;
      }
    }
  }
  return projectName;
}

function handleDonwload(val) {
  const projectName = val._load
  const msg = ElMessage.info(t('alertStr.downloadingStr'))
  const url = `/protocol/export_project?project=${projectName}`
  console.log('下载', projectName, url)
  downloadFile(url).finally(() => {
      msg.close()
  })
}

/**
 * 点击删除项目的按钮事件
 * @param val
 */
function handleDelete(val) {
  const projectName = val._load
  const alertStr = t('alertStr.confirmDeleteProject') + ' [' + projectName + '] ？'
  ElMessageBox.confirm(alertStr, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteProject(projectName)
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

/**
 * 删除项目方法
 * @param projectName
 */
function deleteProject(projectName) {
  reqGetProjectList().then((data) => {
    const jsonData = $x2js.xml2js(data) || defaultProjectList;
    const projectArr = [];
    if (jsonData.workspace && jsonData.workspace && jsonData.workspace.project) {
      if (!jsonData.workspace.project.length) {
        jsonData.workspace.project = [jsonData.workspace.project]
      }
      for (let index = 0; index < jsonData.workspace.project.length; index++) {
        const element = jsonData.workspace.project[index]
        if (element) {
          if (element._load == projectName) {
            jsonData.workspace.project.splice(index, 1);
          } else {
            projectArr.push(element._load);
          }
        }
      }
    } else {
      jsonData.workspace.project = [];
    }
    if (jsonData.workspace.project.length == 0) jsonData.workspace = {};
    const jsontoXML = $x2js.js2xml(jsonData);
    reqSetProjectList({data: jsontoXML}).then((res) => {
      if (res.setProjectList != 0) {
        updateProjectList(jsontoXML)
        reqCheckProjectList().then(() => {
          ElMessage.success(t('successTip'))
        })
      } else {
        ElMessage.error(t('errorTip'))
      }
    }).catch(() => {
      ElMessage.error(t('errorTip'))
    })
  })
}

/**
 * 启用按钮点击事件
 * @param val
 * @param project
 */
function handleStart(val, project) {
  // 点击状态为启用时
  if (val == '1') {
    console.log('启用', project)
    reqGetProjectList().then((data) => {
      const jsonData = $x2js.xml2js(data) || defaultProjectList;
      let existFlag = false
      const projectArr = []
      if (jsonData.workspace && jsonData.workspace && jsonData.workspace.project) {
        if (!jsonData.workspace.project.length) {
          jsonData.workspace.project = [jsonData.workspace.project]
        }
        for (var index = 0; index < jsonData.workspace.project.length; index++) {
          var element = jsonData.workspace.project[index];
          projectArr.push(element._load);
          if (element._load == project) {
            element._active = "1";
            existFlag = true;
          } else {
            element._active = "0";
          }
        }
      } else {
        jsonData.workspace = {
          project: []
        };
      }
      if (!existFlag) {
        jsonData.workspace.project.push({
          "_active": "1",
          "_load": project
        })
      }
      const jsontoXML = $x2js.js2xml(jsonData)
      console.log('转换后xml', jsontoXML)
      reqSetProjectList({data: jsontoXML}).then(() => {
        ElMessage.success(t('successTip'))
      }).catch(() => {
        ElMessage.error(t('errorTip'))
      }).finally(() => {
        updateProjectList(jsontoXML)
      })
    })
  }
}
</script>

<style scoped>
.action-img {
  width: 20px;
  height: 20px;
}

.form-label span:nth-child(2) {
  color: #717289;
}

.form-label {
  font-size: 14px;
  color: #161940;
}

.file {
  width: 480px;
  height: 80px;
  background-color: #F5F6FA;
  border: #A0A2B9 1px dashed;
  border-radius: 4px;
}

.content-title {
  /*padding-left: 10px;*/
  padding-bottom: 15px;
  font-family: "Microsoft YaHei";
  /*margin-top: 10px;*/
  font-size: 17px;
  color: #161940;
  font-weight: bold;
}
</style>